<template>
    <div id="p_taskDetail" class="p_task">
        <popup-picker v-show="false" :show.sync="showTimeNeed" @on-hide="onTimeNeed" title="任务时长" v-model="timeNeed" :data="timeArr" :display-format="format"></popup-picker>        
        <actionsheet v-model="showRemind" :menus="remindBtns" show-cancel @on-click-menu="chooseRemind"></actionsheet>
        <actionsheet v-model="showRemindType" :menus="remindTypeBtns" show-cancel @on-click-menu="chooseRemindType"></actionsheet>        
        <popup-picker :show.sync="showRemind2" :title="remindTitle" :data="remindlist" v-model="remindValue" style="display:none"></popup-picker>

        <sticky scroll-box="vux_view_box_body" :offset="0">
             <transition name="fadeUp" tag="ul" class="list-group">
                <div v-show="taskitem && (taskitem.state=='started'||taskitem.state=='toggle')" style="background-color:#fff;padding-top:8px;" >
                    <div style='width:100px;height:100px;display:flex;margin: 0 auto; '> 
                      <x-circle :percent="timePercent" :stroke-width="6" :trail-width="6" :stroke-color="strokeColor2" trail-color="#ececec">
                        <span :style="{color: strokeColor2}">{{timeDown }}</span> <!-- >0?timeDown.formatTime2():('-'+ timeAdd.formatTime2()) -->
                      </x-circle>
                      <!-- <img v-bind:class="{shake:showAdd}" class="icon iconfont icon-add shake-vertical-slow shake-constant" style="height:100px;" src="/static/z39h5/images/clockImg.png" /> -->
                    </div>

                    <grid class="tagBtns" :cols="showAdd?4:3" style="margin-top:8px;">
                      <grid-item :class="{active: dueDone !=''}">
                        <span class="icon iconfont icon-jihua"></span>
                        <span class="grid-center">{{timeHM(dueDone)||"预计完成"}}</span>
                      </grid-item>
                      <grid-item :class="{active: remindTime !=''}" @click.native="doRemind">
                        <span class="icon iconfont icon-shizhong"></span>
                        <span class="grid-center">{{timeHM(remindTime)||"提醒时间"}}</span>
                      </grid-item>
                      <grid-item :class="{active: remindType !=''}" @click.native="doRemindType">
                        <span class="icon iconfont icon-kuaijiefangshi"></span>
                        <span class="grid-center">{{remindType||"提醒方式"}}</span>
                      </grid-item>
                      <grid-item v-show="showAdd" v-bind:class="{active: remindType !=''}" @click.native="doTimeAdd">
                        <span v-bind:class="{shake:showAdd}" class="icon iconfont icon-add shake-vertical-slow shake-constant"></span>
                        <span class="grid-center">{{"加时"}}</span>
                      </grid-item>
                    </grid>
                </div>
            </transition>
            <group >    
                <x-input v-model="taskTitle" placeholder="任务名" >                
                    <span slot="label" style="padding-right: 6px;color: #10aeff;" class="iconfont icon-renwu1"></span>
                </x-input>
                <x-textarea class="taskDesc" v-model="taskDesc" placeholder="描述信息" :show-counter="false" :rows="3">
                    <span slot="label" style="padding-right: 6px;color: #10aeff;" class="iconfont icon-xingchengmiaoshu"></span>
                </x-textarea>                
                <div v-show="showSave" style="padding:4px">
                    <flexbox :gutter="2" wrap="wrap">
                      <flexbox-item>
                        <x-button type="primary" @click.native="doSave" >保存</x-button></flexbox-item>
                      <flexbox-item>
                        <x-button type="primary" @click.native="doCancle" >取消</x-button></flexbox-item>
                    </flexbox>
                </div>

                <grid class="tagBtns" :cols="taskitem && taskitem.pid?4:3">
                  <grid-item v-if="taskitem && taskitem.pid" :class="{active: to !=''}" @click.native="doMember">
                    <span class="icon iconfont icon-zhaopin1"></span>
                    <span class="grid-center">{{to||"负责人"}}</span>
                  </grid-item>
                  <grid-item :class="{active: due !=''}" @click.native="doDue">
                    <span class="icon iconfont icon-pingguhuizhang"></span>
                    <span class="grid-center">{{timeHM(due)||"开始闹铃"}}</span>
                  </grid-item>
                  <grid-item :class="{active: need !=''}" @click.native="doNeed">
                    <span class="icon iconfont icon-shalou1"></span>
                    <span class="grid-center">{{need||"评估耗时"}}</span>
                  </grid-item>
                  <grid-item :class="{active: remind !=''}" @click.native="doRemind2">
                    <span class="icon iconfont icon-shizhong"></span>
                    <span class="grid-center">{{remind?(remind+"m"):"提醒方式"}}</span>
                  </grid-item>
                </grid>

                <div class="flagshow" @click="doTagChange">
                    <div style="display:flex;">
                        <span style="color: #10aeff;">标签</span><span v-if="flagUse.length==0">点击添加</span><span ref="flags" v-for="(it, index) in flagUse" :key="index" :value="it">{{it.name}}</span>
                    </div>
                </div>          
            </group>  

        </sticky>
        <group >    
            <x-input v-model="newTaskTitle" placeholder="新建子任务" placeholder-align="left" class="weui-vcode">
                <span slot="label" style="padding-right: 6px;" class="iconfont icon-add"></span>
                <x-button slot="right" v-show="newTaskTitle.length>0" type="primary" @click.native="doITaskAdd()" mini>确定</x-button>
            </x-input>
        </group> 
        <group v-show="iTaskArr.length">    
            <swipeout>
                <swipeout-item  @on-open="actionOpen(taskDetail, index)"  v-for="(item, index) in taskDetail?[taskDetail]:[]" :key="index" >
                    <div slot="right-menu">
                        <swipeout-button @click.native="onDelClick(item,index)" type="warn">取消任务</swipeout-button>
                    </div>
                    <div slot="left-menu">
                        <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                    </div>
                    <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskitem == item}">
                        <cell @click.native="onAction(item,index)" :title="item.title" :value="item.duration" :inline-desc="item.desc">
                            <img slot="icon" :src="item.img || '/static/z39h5/img/logo.png'">
                        </cell>
                    </div>
                </swipeout-item>
            </swipeout>        
            <swipeout>
                <swipeout-item  @on-open="actionOpen(item, index)"  v-for="(item, index) in iTaskArr" :key="index" ref="action" >
                    <div slot="right-menu">
                        <swipeout-button @click.native="onDelClick(item,index)" type="warn">取消</swipeout-button>
                    </div>
                    <div slot="left-menu">
                        <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                    </div>
                    <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskitem == item}">
                        <cell @click.native="onAction(item,index)" :title="item.title" :value="item.duration" :inline-desc="item.desc">
                          <div slot="icon">
                              <img :src="showIcons(item)" style="width:50px;height:50px;"/>
                              <span class="taskCount">{{index+1 + "/" + iTaskArr.length}}</span>
                          </div>
                        </cell>
                    </div>
                </swipeout-item>
            </swipeout>        
        </group>  
        <div v-show="!showSave" class="taskBtns">
            <flexbox :gutter="4" wrap="wrap">
              <flexbox-item v-if="taskState!='started'&&taskState!='toggle'&&taskState!='done'"><x-button type="primary" @click.native="doStart" >开始</x-button></flexbox-item>
              <flexbox-item v-if="taskState=='toggle'"><x-button type="primary" @click.native="doToggle(true)" >继续</x-button></flexbox-item>
              <flexbox-item v-if="taskState=='started'"><x-button type="primary" @click.native="doToggle(false)" >暂停</x-button></flexbox-item>
              <!-- <flexbox-item v-if="taskState!='done'"><x-button type="primary" @click.native="" >取消</x-button></flexbox-item> -->
              <flexbox-item v-if="taskState!='done'"><x-button type="primary" @click.native="doDone" >完成</x-button></flexbox-item>
              <flexbox-item v-if="taskState=='done'"><x-button type="primary" @click.native="onTaskMend" >修改</x-button></flexbox-item>
              <flexbox-item v-if="taskState!='done'"><x-button  type="primary" @click.native="doHelp" >求助</x-button></flexbox-item>
              <flexbox-item v-if="taskState=='done'"><x-button type="primary" @click.native="doSummary" >总结</x-button></flexbox-item>
            </flexbox>
        </div>


        <flags v-on:flaghide="onflagHide" :show.sync="showAddTag" :task="taskitem"></flags>

        <t-summary :task="taskitem || defaultTask" :show.sync="showSummary"></t-summary>        
    <!-- :v-model="showSummary" -->
    </div>
</template>
<script>
import moment from "moment";

// import TCell from "./t-cell/index.vue"
import TSummary from "./task/TSummary.vue"
import Flags from "./task/Flags.vue"

import api from '../api';
import { taskAndTag  } from "./mixin";
import { help  } from "./mixinApp";
import { logic  } from "./mixinTaskLogic";

// let defaultTask ={title:"",desc:""} ;
let remindBtnsDef = [  {label: '提前时间<br/><span style="color:#666;font-size:12px;">任务结束前提前几分钟提醒</span>',type: 'info'},{label: '提前05分钟',value: '5'  }, 
                {    label: '提前10分钟',value: '10'  }, 
                {    label: '提前15分钟',value: '15'  }, 
                {    label: '提前20分钟',value: '20'  }];
let remindTypeBtnsDef = [ {label: '闹钟提醒方式<br/><span style="color:#666;font-size:12px;">任务结束前和超时共2次提醒</span>',type: 'info'},
                {label: '系统闹钟',value: '1'  }, 
                {    label: '公众号提醒',value: '2'  }, 
                {    label: 'APP消息',value: '3'  }, 
                {    label: '短信提醒',value: '4'  }, 
                {    label: '电话呼叫',value: '5'  }];
let remindTime1 = ['不提醒','提前05分钟', '提前10分钟', '提前15分钟', '提前20分钟', '提前25分钟', '提前30分钟'] ;
let remindType1 = ['系统闹钟', '公众号提醒', 'APP消息', '短信提醒', '电话呼叫'] ;

require('vue2-animate/dist/vue2-animate.min.css')
// import 'vue-animate/dist/vue-animate.min.css'
import {
    mapState,
    mapActions
} from 'vuex'
import Vue from 'vue';

import {
    Tab,TabItem, Grid,GridItem,Popup,Icon,Actionsheet,Checker,CheckerItem,Divider,XCircle,Countdown, PopupPicker,Cell,
    TransferDomDirective as TransferDom,
    Toast,
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    XButton,
    Group,
    Picker,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,
      ButtonTab,    ButtonTabItem,
    Scroller,
    Sticky
} from 'vux'

export default {
    directives: {
        TransferDom
    },
    components: {
        Tab,TabItem,Grid,GridItem,Popup, Icon,Actionsheet,Checker,CheckerItem,Divider,XCircle,Countdown,PopupPicker,Cell,
        Toast, TSummary,Flags, //TCell,
        Swipeout,
        SwipeoutItem,
        SwipeoutButton,
        XButton,
    Group,
    Picker,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,
    ButtonTab,    ButtonTabItem,
    Scroller,
    Sticky
    },
    mixins: [taskAndTag,help,logic],    
    computed: {
        // testTasks: function() {  //测试今日数据立刻改变
        //     var tempDay = this.daySelect ; // moment().format("YYYY-MM-DD");
        //     console.log("asdf");
        //     return this.taskAll.filter(function (task) {return task.tags && task.tags["need"]} );
        // },
        ...mapState({
            uid: state => state.vux.uid,
            openid: state => state.vux.openid,
            phone: state => state.vux.phone,            
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
            
            tagitems: state => state.z39.tagitems,
            tagitemDic: state => state.z39.tagitemDic,
            taskDetail: state => state.z39.taskDetail,
            taskRunId: state => state.z39.taskRunId,
            taskRunTitle: state => state.z39.taskRunTitle,
        })
    },
    watch: {
        // "$route.params":function(){
        //     if( _.isEmpty(this.$route.params.id) ){
        //         return ;
        //     }
        //     this.getData();
        // },
        "taskDetail":{
            handler(){
                if(this.taskDetail==null) return ;
                // console.log("iTaskArr", _.clone(this.taskitem), this.taskDetail);
                if( this.taskitem == null  ){  //|| this.taskDetail.id == this.id
                    this.taskitem = this.taskDetail ;
                    console.log("change task in",this.taskDetail);
                }
                var temp= [] ;            
                if( !_.isEmpty(this.taskDetail) && !_.isEmpty(this.taskDetail.tasks) ){
                    temp = this.taskDetail.tasks  ;
                }
                if( this.taskitem && this.taskDetail.id == this.taskitem.id ){
                    Object.assign(this,this.getDone2Due(this.taskitem));
                    this.doCountDown();
                }
                this.iTaskArr = temp ;
            },deep:true},
        "showSummary":function(){
            console.log("showSummary:",this.showSummary) ;
        },
        "taskitem":{
            handler(){   //监听手机版标签弹窗关闭
                if(this.taskitem == null){                    
                    this.taskTitle = "" ;
                    this.taskDesc = "" ;
                    this.to = ''; 
                    this.due = '' ;
                    this.need = ''; 
                    this.started = '' ;
                    this.remind =  '';
                    this.flagUse = [] ;
                    this.clearCountdown();
                    return ;
                }
                this.taskTitle = this.taskitem.title ;
                this.taskDesc = this.taskitem.desc ;
                this.showSave = false ;
                this.taskitem.tags = this.taskitem.tags || {} ;
                this.taskState = this.taskitem.state || '' ;

                this.to = this.taskitem.tags["to"] || ''; 
                let tempdue = this.taskitem.tags["due"] || ''; 
                this.due = tempdue ; //.length > 11 ? tempdue.substring(11):'' ;
                var tempNeed = this.taskitem.tags["need"];
                this.need = tempNeed?(formatTimeHM(tempNeed)):''; 
                if(this.need) this.timeNeed = this.need.split(":");
                this.started= this.taskitem.tags["started"] || ''; 
                if( this.taskitem.tags["remind"] ){
                    var tempR  = this.taskitem.tags["remind"] ;
                    var tempA  = tempR.split("_") ;
                    this.remind = tempA[0] ;
                    this.remindTypeValue = tempA[1];
                    var tempt = parseInt(tempA[1]||1) ; // 
                    tempt = remindTypeBtnsDef[tempt].label;
                    this.remindType = tempt.substr(0,tempt.length-2);
                    this.changeRemindSelect();
                }else{
                    this.remind = '';
                }
                
                var temp = [];
                var filtersFlag = ["created", "started", "need", "done", "toggle", "cancelled", "due", "used", "usedCalc", "to", "repeat", "critical","timeDiff"] ;
                for(var key in this.taskitem.tags){
                    if(filtersFlag.indexOf(key) == -1){
                        temp.push({name: this.tagitemDic[key],value:key});
                    }
                }
                this.flagUse = temp ;

                Object.assign(this,this.getDone2Due(this.taskitem));
                this.doCountDown();

                console.log("tagitem:",temp,_.clone(this.taskitem),_.clone(this.taskitem.tags),this.to,this.due,this.need,this.remind) ;
            },deep:true
        },
        "tagitems":function(){
            var temp = [],ischange=false;
            var len = this.flagUse.length ;
            for(var i=0;i<= len-1 ;i++){
                var item = this.flagUse[i] ;
                if( !_.isEmpty(item.name) ){
                    continue ;
                }
                ischange = true ;
                item.name = this.tagitemDic[item.value] ;
            }
        },
        "taskTitle":function(){
            this.doWatchSave();
        },
        "taskDesc":function(){
            this.doWatchSave();
        },
        "uid":function(){
            this.getInitData();
        },
        "remindValue":function(){
            var temp,temp1 ;
            temp = this.remindName2Val(this.remindValue[0],1);
            temp1 = this.remindName2Val(this.remindValue[1],2);            
            if(this.remind == temp && this.remindTypeValue == temp1) return ;
            const _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向
            if(temp1 == 2 && !this.noticeData.wx) {
                this.$vux.confirm.show({
                  title:"关注7天时间清单",
                  content:"微信提醒功能,关注公众号自动开通提醒功能.自动切换为'系统闹钟'.点击确定去关注",
                  onCancel () {
                    _this.$vux.toast.show({text:"已切换系统提醒",type:"warn"})
                  },
                  onConfirm () {
                    console.log("go to") // _this 当前 vm
                  }
                })
                temp1 = 1 ; //自动切换为'系统提示'
            }
            if(temp1 == 3 && !isApp) { //不是App
                // this.$vux.toast.show({text:"APP可用,已换系统提醒",type:"warn"})
                this.$vux.confirm.show({
                  title:"APP里使用",
                  content:"时间清单APP.如已绑定手机,会收到下载短信.已切换为系统提醒",
                  onCancel () {
                    
                  },
                  onConfirm () {
                    
                  }
                })
                temp1 = 1 ; //自动切换为'系统提示'
            }
            if( (temp1 == 4 ||temp1 == 5) && !this.phone) {
                this.$vux.confirm.show({
                  title:"缺手机号码",
                  content:"功能需要先输入您号码.点击确定去绑定手机",
                  onCancel () {
                    _this.$vux.toast.show({text:"已切换系统提醒",type:"warn"})
                  },
                  onConfirm () {
                    _this.go("bind");
                    _this.$vux.toast.show({text:"绑定后重新设置",type:"warn"})
                  }
                })
                temp1 = 1 ; //自动切换为'系统提示'
            }
            this.remind = temp ;
            this.remindTypeValue = temp1;
            var name = this.remindValue[1] ;
            this.remindType = name.substr(0,name.length-2);
            console.log("remindlist:",this.remindValue,this.remind,this.remindType);
            localStorage.setItem("remind",this.remind);
            localStorage.setItem("remindTypeValue",this.remindTypeValue);
            // 刚进入页面因回复上次设置的提醒值,进入逻辑但taskitem ==null
            if(this.taskitem) this.changeRemind(this.taskitem,this.remind,this.remindTypeValue);
        },
    },
    activated () {
        this.getData();
    },
    deactivated(){
        this.iTaskArr = [];
        this.taskTitle = "" ;
        this.taskDesc = "" ;
        this.taskitem = null ;
    },
    created() {        
        this.getInitData();
    },
    filters:{
        timeFormat: function (time) {  
          try{
            time = time.formatTime2();
          }catch(e){}
          return  time ; 
        }  
    },
    mounted: function() {
        var type = localStorage.getItem("remindTypeValue") ;
        type = type || (isApp?3:1) ;
        type = parseInt(type);
        var item = remindTypeBtnsDef[type]; //
        var tempRemind = localStorage.getItem("remind") || 0 ; //5 分钟
        tempRemind = parseInt(tempRemind);
        this.remind = tempRemind !=0?tempRemind: 5;
        this.remindTypeValue = type;
        this.remindType = item.label.substr(0,item.label.length-2)
        var temp = remindTime1[tempRemind/5] ; //0  5 15 20 25 30
        var temp1 = item.label ;
        this.remindValue = [temp,temp1];
    },
    methods: {
        getInitData(){
            // if(this.uid==0)return ;  //便于兼职查看任务详情
            if( _.isEmpty(this.tagitemDic) ){
                this.tagitemsGet();
            }
            this.getData();
        },
        getData: function() {            
            this.id = this.$route.params.id ;
            let tid = this.id  ;
            console.log("task id",tid);
            if(tid){
                if( this.taskitem && this.taskitem.id != tid ){
                    this.taskitem = null ;
                    console.log("change task");
                }
                this.taskGet(this.$route.params.id) ;
            }
            let noticeDay = localStorage.getItem("noticeDay") || "" ;
            var today = moment().format("YYYY-MM-DD");
            if( today != noticeDay){
                api.noticeStateGet().then(data=>{
                    if(data.errno !=0) return ;
                    data = data.data ;
                    localStorage.setItem("noticeDay",today);
                    localStorage.setItem("noticeData",JSON.stringify(data));
                    this.noticeData = data ;
                })                
            }else{
                var temp = localStorage.getItem("noticeData") ;
                this.noticeData = JSON.parse(temp) ;
            }
        },
        onflagHide:function(val) {
            this.showAddTag = val ;
        },
        dueChange(val){            
            // console.log("monthChange",val) ;
            // this.doTaskEdit(this.taskitem,"due",val);
        },
        onTimeNeed(value){
            this.showTimeNeed=false ;
            if(!value) return ; //点击取消
            let doneMom = moment().add(this.timeNeed[0],'h').add(this.timeNeed[1],'m') ;
            let doneStr = doneMom.format('YYYY-MM-DD HH:mm') ;
            let time = this.timeNeed.join(":");
            if( !this.timeShowAdd ){  //评估时间
                this.need = time ;
                this.doTaskEdit(this.taskitem,"need" , getSecond(time) ).then((data)=>{
                    this.checkSetClock(this.taskitem);
                });
                // this.getDone2Due() ;
            }else{  //添加时间.
                let res = this.timeAddCalc(this.need,time);                
                this.doTaskEdit(this.taskitem,"need" , getSecond(res) ).then((data)=>{
                    this.checkSetClock(this.taskitem);
                });
                // console.log("do add",doneStr,this.need,time,res); 
            }
            this.doCountDown();
        },
        doTagChange(){
            this.showAddTag = true ;
            // setTimeout(()=>{
            //     this.showAddTag = true ;
            // },10)
        },
        chooseRemind (key, item) {
          console.log("chooseEdit",key, item,item.value) ;
          if( item == undefined)return ; //点击取消.
          this.remind = item.value ;
          this.changeRemind(this.taskitem,this.remind,this.remindTypeValue);
          // this.getDone2Due() ;
        },
        changeRemindSelect(){  //修改弹出闹钟显示的文字
            // remindValue:['提前05分钟', '系统闹铃'],
            var index = this.remind/5 ;
            var temp = index<4?(index==0?"不提醒":remindBtnsDef[index].label):`提前${this.remind}分钟` ;
            var temp1= remindTypeBtnsDef[this.remindTypeValue].label ;
            this.remindValue = [temp,temp1];
        },
        changeRemind(task,remind,remindValue){
            if(!task) return ; //刚今日页面
            var value = `${remind}_${remindValue}` ;
            if(task["tags"]==undefined || value == task.tags.remind) return ;
            this.doTagSet( task , "remind", value ).then((data)=>{
                this.checkSetClock(task);
            })
            
        },
        chooseRemindType (key, item) {
          console.log("chooseEdit",key, item,item.value) ;
          if( item == undefined) return ;//点击取消.
          localStorage.setItem("remindTypeValue",item.value);
          this.remindTypeValue = item.value ;
          this.remindType = item.label.substr(0,item.label.length-2) ;
          this.changeRemind(this.taskitem,this.remind,this.remindTypeValue);
          // this.getDone2Due() ;
        },
        doHelp(){
            this.$vux.toast.show({text:"暂未开放" ,type: 'warn'});
        },
        onTaskMend(){
            if(!this.uid) return this.$vux.toast.show({text:"请先登录" ,type: 'warn'});
            this.doTaskMend(this.taskitem) ;
        },
        doSummary(){
            if(!this.uid) return this.$vux.toast.show({text:"请先登录" ,type: 'warn'});
            
            this.$vux.bus.$emit('taskAddExtOnce', {parid:this.taskDetail.id,state:"done",tags:{summary:""}});
            this.$vux.bus.$emit('taskAddVisible', true);
            // this.showSummary = true ;
            console.log("doSummary",this.showSummary);
        },
        doStart(){
            this.taskState = "started" ;
			var startedVal = moment().format("YYYY-MM-DD HH:mm") ;
            this.doTaskEdit( this.taskitem,"started",startedVal ).then((data)=>{
                this.checkSetClock(this.taskitem,startedVal); 
            });
        },
        doUnDone(){
            this.taskState = "" ;
            this.doTaskEdit( this.taskitem,"",moment().format("YYYY-MM-DD HH:mm") );
        },
        doToggle(begin){ 
            this.taskState = begin?"started":"toggle";
            if(begin){

            }
            this.doTaskEdit( this.taskitem,"toggle",moment().format("YYYY-MM-DD HH:mm") );
        },
        doDone(){
            this.taskState = "done" ;
            this.doTaskEdit( this.taskitem,"done",moment().format("YYYY-MM-DD HH:mm") );
        },
        doMember(){

        },
        doSave(){
            this.taskSet({title:this.taskTitle,desc:this.taskDesc,id:this.taskitem.id},this.taskitem);
        },
        doCancle(){            
            this.taskTitle = this.taskitem.title ;
            this.taskDesc = this.taskitem.desc ;
        },
        doDue(){
            let temp = moment().add(1,"H").format("YYYY-MM-DD HH:mm") ;
            let dueCurr = this.taskitem&& this.taskitem.tags?this.taskitem.tags['due'] :temp; //this.due ; //
            let _this = this ;
            this.$vux.datetime.show({
                cancelText: '取消',
                confirmText: '确定',
                format: 'YYYY-MM-DD HH:mm',
                minuteList:['00','05','10', '15','20','25', '30','35','40','45','50','55'],
                clearText:'清除',
                startDate: moment().format("YYYY-MM-DD") ,
                value: dueCurr ,
                onConfirm (val) {
                  _this.due =  val.substring(11) ;
                  _this.doTaskEdit( _this.taskitem ,"due",val);
                },
                onShow () {
                  console.log('plugin show')
                },
                onHide () {
                  console.log('plugin hide')
                },
                onClear(){
                    _this.tagsDel(["due"],false,_this.taskitem);
                }
              })
        },
        doNeed(){
            this.showTimeNeed = true ;
            this.timeShowAdd = false ;
        },
        doTimeAdd(){
            this.showTimeNeed = true ;
            this.timeShowAdd = true ;
        },
        doRemind(){ //提醒
            this.showRemind = true ;
        },
        doRemind2(){ //提醒
            this.showRemind2 = true ;
        },
        doRemindType(){ //设置提醒方式
            console.log("doRemindType");
            this.showRemindType = true ;
        },
        doWatchSave(){
            if(this.taskitem == null){
                this.showSave = false ;
                return ;
            }
            this.showSave = (this.taskTitle != this.taskitem.title || this.taskDesc != this.taskitem.desc)?true:false ;
        },
        actionOpen(item,index){            
            let dir = "" , target , arrIndex = index ;
            target = this.$refs.action[index] ;
                dir = target.direction ;
            if( dir == "left"){
                if( item.state == "done"){
                    this.doTaskEdit(item,"");
                }else{
                    this.doTaskEdit(item,"done",moment().format("YYYY-MM-DD HH:mm"));
                }
                setTimeout(() => {
                    target.close();
                }, 200);                
            }
        },
        onAction(item,index){
            this.taskitem = item ;
        },
        onDelClick( item, index) {
            console.log(item);
            this.doTaskEdit(item,"cancelled",moment().format("YYYY-MM-DD HH:mm"));
        },
        doITaskAdd(){
            let sdata = {title:this.newTaskTitle} ;            
            sdata.parid = this.taskDetail.id ;
            let tags =  {created:moment().format('YYYY-MM-DD HH:mm')} ;
            this.taskAdd(sdata,tags).then(data => {
                let task = data;
                if(this.taskDetail.tasks==undefined) Vue.set(this.taskDetail,"tasks",[])
                this.taskDetail.tasks.push(task);
                this.$store.commit({ type: "z39/taskToDB", tasks: [task], act: "add" });
                this.newTaskTitle = '';
            });  
        },
        doCountDown(){
            this.clearCountdown();
            let leftTime = -moment().diff(this.dueDone)/1000 || 0;   //距离完成的剩余时间,单位秒
            let used = 0 ;
            let needSecond = this.toSecond( this.need) ;
            if( this.taskitem.tags && this.taskitem.tags["used"] ){
                used = this.taskitem.tags["used"]  || "";
                let past = this.toSecond(used);
                let restart = this.taskitem.tags["toggle"] ;
                if( this.taskitem.state=="started" && restart ){
                    past += moment().diff(restart)/1000 ;
                }
                this.timeAdd = past ;
                
                this.showCountDown(leftTime,needSecond);
            }
            if( this.taskitem.state != "started"){
                return ;
            }
            this.timeAddIntId = setInterval(()=>{
                this.timeAdd ++ ;
                this.showCountDown(leftTime,needSecond);
            },1000);            

        },
        showCountDown(leftTime,needSecond){
            let temp = leftTime - this.timeAdd ;
            // console.log("countdown:",Math.abs(temp).formatTime2() , this.timeAdd , leftTime , leftTime.formatTime2() ,this.dueDone );
            this.timePercent = Math.floor(temp / needSecond *100) ;
            if( temp >= 0 ){
                this.showAdd  = false ;
                this.strokeColor2 = "#10aeff" ;
                this.timeDown = temp.formatTime2() ;

            }else{
                this.showAdd = true ;
                this.strokeColor2 = "#e64340" ;
                this.timePercent = 100 ;
                this.timeDown = "-"+Math.abs(temp).formatTime2() ;
            }
            // console.log("used",this.timePercent,Math.abs(leftTime - this.timeAdd).formatTime2());
        },
        toSecond(timeStr){ //转换成秒. 10:00 10分钟,  timeStr单位是 时:分
            let res = 0;
            if(timeStr.indexOf(":")>-1){
                let temp = timeStr.split(":");
                res = parseInt(temp[0])*60*60 +parseInt(temp[1])*60 ;
            }
            return res;
        },
        clearCountdown(){
            if(this.timeAddIntId >-1){
                clearInterval(this.timeAddIntId) ;
                this.timeAddIntId = -1 ;
            }
            this.timeAdd = 0 ;
        },
        timeHM: function (time) {
            var str ;
            if(time.length>10){
                str = time.substring(11) ;
            }else if(time.length>5){
                str = time.substring(5) ;
            }else{
                str = time
            }
            return str;
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            id:0,
            iTaskArr:[],
            // taskArr:[],
            newTaskTitle:"",
            taskTitle:"",
            taskDesc:"",
            to:"",
            due:"",
            started:"",
            need:"",
            remind:"",
            defaultTask:{title:"",desc:""} ,
            taskitem: null , //defaultTask, // null , //
            flagUse:[{name: "评估",key:"need"}],
              showAddTag:false,
            tagsOld:[],
            showSummary:false ,
              smyTitle:"",
              smydesc:"",
              smydesc1:"",
              smydesc2:"",
              smydesc3:"",
              smydesc4:"",
              smydesc5:"" ,

            visibility: false ,            
            timeNeed:["00","30"],
            timeArr:[['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],['05','10','15','20','25','30','35','40','45','50','55']] ,
              format: function (value, name) {
                return `${value[0]}:${value[1]}`
              },
              showTimeNeed:false ,
              showPopupPicker: false,
              today:moment().format("YYYY-MM-DD"),
              showRemind:false,
              remindBtns:remindBtnsDef,
              remindTypeBtns:remindTypeBtnsDef,
              showRemindType:false,
              remindTime:'',
              remindType:'', //'',
              remindTypeValue:1,
              remindTitle:"设置任务提醒",
              remindValue:['提前05分钟', '系统闹钟'],
              remindlist:[remindTime1,remindType1],
              showRemind2:false,
              taskState:"done", //  "", // 
              showSave:false ,
              timePercent: 30,
              strokeColor2: '#3FC7FA',
              timeDown:'00:00',
              showAdd:false,
              timeAdd:0,
              timeAddIntId:-1,
              leftTime:0,
              dueDone:'',
              noticeData:{},
        }
    }
}

</script>
<style scoped>

.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}

#p_taskDetail .active .iconfont {
    color: #10aeff;
}

</style>
<style>
#p_taskDetail .taskDesc textarea{
    padding-top: 2px;
}
#p_taskDetail .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
.grid-center {
  display: block;
  text-align: center;
  color: #666;
}
#p_taskDetail .tagBtns{
    height: 40px;
 }
#p_taskDetail .tagBtns a{
    line-height: 40px;
    height: 40px;
    padding: 0;
    display: flex;
}
/*#p_taskDetail .tagBtns a svg{
    padding: 8px 0;
}*/
#p_taskDetail .tagBtns a .iconfont{
    width: 38px;
    text-align: center;
    color: #000;
 }

#p_taskDetail .taskBtns{
    width: 100%;
    padding: 4px;
    position:fixed; bottom:0;
    background-color: #fff;
}
#p_taskDetail{
    margin-bottom: 52px;
}

</style>
